package com.fbt.transfer.app.driver.ui.grab;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fbt.transfer.app.driver.R;
import com.fbt.transfer.app.driver.model.OrderTypeEnum;
import com.fbt.transfer.app.driver.model.grab.WaitOrderUnit;
import com.ncorti.slidetoact.SlideToActView;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 抢单大厅订单列表适配器
 */
public class GrabOrderAdapter extends RecyclerView.Adapter<GrabOrderAdapter.ViewHolder> {

  private static final String TIME_FORMAT = "HH:mm";
  private final List<WaitOrderUnit> orderList = new ArrayList<>();
  private final Context context;
  private OnItemClickListener onItemClickListener = null;
  private OnGrabClickListener onGrabClickListener = null;
  private boolean beautifyCard = false;
  private final SimpleDateFormat dateFormat = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm", Locale.getDefault());

  public GrabOrderAdapter(Context context) {
    this.context = context;
  }

  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context)
        .inflate(R.layout.layout_grab_order_item, parent, false);
    return new ViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    WaitOrderUnit order = orderList.get(position);
    // 设置订单类型
    holder.llFlight.setVisibility(View.GONE);
    OrderTypeEnum orderType = OrderTypeEnum.getByValue(order.getOrderType().getValue());
    holder.tvOrderTypeDesc.setText(order.getOrderType().getDesc());
    if (orderType == OrderTypeEnum.PICK_UP) {
      holder.ivStarIcon.setImageResource(R.mipmap.flight);
      holder.ivEndIcon.setImageResource(R.mipmap.order_start_icon);
      holder.llFlight.setVisibility(View.VISIBLE);
      holder.tvFlight.setText(order.getFlightNo());
      holder.tvFlightDate.setText(order.getFlightDate());
      holder.tvOrderTypeDesc.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
    } else {
      holder.ivStarIcon.setImageResource(R.mipmap.order_start_icon);
      holder.ivEndIcon.setImageResource(R.mipmap.flight);
      holder.tvOrderTypeDesc.setTextColor(ContextCompat.getColor(context, R.color.gray_text_color));
    }
    // 设置预约时间
    holder.tvTime.setText(order.getBookTime());
    LocalDateTime bookTime =
        LocalDateTimeUtil.parse(order.getBookTime(), "yyyy-MM-dd HH:mm");
    LocalDate today = LocalDate.now();
    LocalDate bookDate = bookTime.toLocalDate();
    holder.tvTime.setText(order.getBookTime());
    if (bookDate.isEqual(today)) {
      holder.tvTime.setText("今天 " + LocalDateTimeUtil.format(bookTime, TIME_FORMAT));
    } else if (bookDate.isBefore(today)) {
      holder.tvTime.setTextColor(ContextCompat.getColor(context, R.color.gray));
      if (bookDate.until(today, ChronoUnit.DAYS) == 1) {
        holder.tvTime.setText("昨天 " + LocalDateTimeUtil.format(bookTime, TIME_FORMAT));
      }
    } else if (bookDate.isEqual(today)) {
      holder.tvTime.setText("今天 " + LocalDateTimeUtil.format(bookTime, TIME_FORMAT));
    } else if (today.isBefore(bookDate) && today.until(bookDate, ChronoUnit.DAYS) == 1) {
      holder.tvTime.setText("明天 " + LocalDateTimeUtil.format(bookTime, TIME_FORMAT));
    } else if (today.isBefore(bookDate) && today.until(bookDate, ChronoUnit.DAYS) == 2) {
      holder.tvTime.setText("后天 " + LocalDateTimeUtil.format(bookTime, TIME_FORMAT));
    }
    // 设置起点和终点
    holder.tvStarAddress.setText(order.getStartPosition().getDetail());
    holder.tvEndAddress.setText(order.getEndPosition().getDetail());
    holder.tvCarType.setText(order.getCarType().getDesc());
    holder.tvIncome.setText(order.getIncome().toPlainString() + "元");
    holder.tvEstimateMil.setText(
        String.format(
            "预计%sKm", new BigDecimal(order.getEstimateDistance())
                .movePointLeft(3).stripTrailingZeros().toPlainString()
        )
    );

    // 设置已查看状态
    holder.tvViewed.setVisibility(order.getIsViewed() ? View.VISIBLE : View.GONE);

    // 计算并显示剩余时间
    String remainingTime = calculateRemainingTime(order.getBookTime());
    holder.tvSurplusTime.setText(remainingTime);

    // 设置点击事件
    holder.itemView.setOnClickListener(v -> {
      if (onItemClickListener != null) {
        onItemClickListener.onItemClick(order, position);
      }
    });
    // 设置滑块完成事件
    holder.slideToGrab.setOnSlideCompleteListener(
        slideToActView -> {
          if (onGrabClickListener != null) {
            onGrabClickListener.onGrabClick(order, position);
          }
        }
    );
  }

  private String calculateRemainingTime(String bookTime) {
    LocalDateTime appointmentDate = LocalDateTimeUtil.parse(bookTime, "yyyy-MM-dd HH:mm");
    //如果大于1天
    LocalDateTime now = LocalDateTime.now();
    if (!appointmentDate.isAfter(now)) {
      return "已过期";
    }
    long days = now.until(appointmentDate, ChronoUnit.DAYS);
    if (days >= 1) {
      return String.format(Locale.SIMPLIFIED_CHINESE, "%d天后出发", days);
    }
    long diffInMinutes = now.until(appointmentDate, ChronoUnit.MINUTES);
    long diffInHours = diffInMinutes / 60;
    long remainingMinutes = diffInMinutes % 60;
    if (diffInHours > 0) {
      return String.format(
          Locale.getDefault(), "%d小时%d分钟后出发", diffInHours, remainingMinutes);
    } else {
      return String.format(Locale.getDefault(), "%d分钟后出发", diffInMinutes);
    }
  }

  @Override
  public int getItemCount() {
    return orderList.size();
  }

  @SuppressLint("NotifyDataSetChanged")
  public void setData(List<WaitOrderUnit> data) {
    orderList.clear();
    if (data != null) {
      orderList.addAll(data);
    }
    notifyDataSetChanged();
  }

  @SuppressLint("NotifyDataSetChanged")
  public void addData(List<WaitOrderUnit> data) {
    if (data != null) {
      orderList.addAll(data);
      notifyDataSetChanged();
    }
  }

  public void clear() {
    orderList.clear();
    notifyDataSetChanged();
  }

  public static class ViewHolder extends RecyclerView.ViewHolder {

    TextView tvOrderTypeDesc;
    TextView tvSurplusTime;
    TextView tvTime;
    TextView tvStarAddress;
    TextView tvEndAddress;
    TextView tvCarType;
    TextView tvFlight;
    TextView tvFlightDate;
    TextView tvIncome;
    TextView tvEstimateMil;
    SlideToActView slideToGrab;
    TextView tvViewed;
    ImageView ivStarIcon;
    ImageView ivEndIcon;
    LinearLayout llFlight;

    public ViewHolder(@NonNull View itemView) {
      super(itemView);
      tvOrderTypeDesc = itemView.findViewById(R.id.tv_order_type_desc);
      tvSurplusTime = itemView.findViewById(R.id.tv_surplus_time);
      tvTime = itemView.findViewById(R.id.tv_time);
      tvStarAddress = itemView.findViewById(R.id.tv_star_address);
      tvEndAddress = itemView.findViewById(R.id.tv_end_address);
      tvCarType = itemView.findViewById(R.id.tv_car_type);
      tvIncome = itemView.findViewById(R.id.tv_income);
      slideToGrab = itemView.findViewById(R.id.slide_to_grab);
      tvEstimateMil = itemView.findViewById(R.id.tv_estimate_mil);
      tvViewed = itemView.findViewById(R.id.tv_viewed);
      ivStarIcon = itemView.findViewById(R.id.iv_star_icon);
      ivEndIcon = itemView.findViewById(R.id.iv_end_icon);
      tvFlight = itemView.findViewById(R.id.tv_flight);
      llFlight = itemView.findViewById(R.id.ll_flight);
      tvFlightDate = itemView.findViewById(R.id.tv_flight_date);
    }
  }

  public interface OnItemClickListener {

    void onItemClick(WaitOrderUnit order, int position);
  }

  public interface OnGrabClickListener {

    void onGrabClick(WaitOrderUnit order, int position);
  }

  public void setOnItemClickListener(OnItemClickListener listener) {
    this.onItemClickListener = listener;
  }

  public void setOnGrabClickListener(OnGrabClickListener listener) {
    this.onGrabClickListener = listener;
  }

  public void setBeautifyCard(boolean beautifyCard) {
    this.beautifyCard = beautifyCard;
  }
}